#!/usr/bin/env python3
# coding: utf-8

'''
pip install json-rpc werkzeug
'''


from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
from jsonrpc import JSONRPCResponseManager, Dispatcher


'''
@dispatcher.add_method
def foobar(**kwargs):
    return kwargs["foo"] + kwargs["bar"]

openssl genrsa -out ca-key.pem 1024
openssl req -new -out ca-req.csr -key ca-key.pem
openssl x509 -req -in ca-req.csr -out ca-cert.pem -signkey ca-key.pem -days 3650

#openssl pkcs12 -export -clcerts -in ca-cert.pem -inkey ca-key.pem -out ca.p12


curl -k -i -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0", "method":"echo", "params":["name","I am mark"], "id":"200"}' https://127.0.0.1:4004
'''


class CommonJsonrpcServer():
    def __init__(self):
        self.dispatcher = Dispatcher()


    def regist(self, objordic):
        self.dispatcher = Dispatcher(objordic)


    @Request.application
    def application(self, request):
        # Dispatcher is dictionary {<method_name>: callable}
        response = JSONRPCResponseManager.handle(request.data, self.dispatcher)
        return Response(response.json, mimetype='application/json')


    def start(self, port:int = 4004, ssl_context = None):
        #run_simple('0.0.0.0', port, self.application)
        run_simple('0.0.0.0', port, self.application, ssl_context=ssl_context)


if __name__ == '__main__':
    class Test():
        def echo(self, parm):
            return parm

    s = CommonJsonrpcServer()
    t = Test()
    s.regist(t)
    s.start()
    #s.start(ssl_context = ('ssl.cert', 'ssl.key'))
